package com.dongdongshop.shiro;


import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.SellerService;
import com.dongdongshop.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @ClassName PersonRealm
 * @Author RC
 * @date 2020.12.07 11:20
 */
public class UserLoginRealm extends AuthorizingRealm{
    @Reference
    private UserService userService;
    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权方法");
        //获取登录用户
        Subject subject = SecurityUtils.getSubject();
        TbUser tbUser = (TbUser) subject.getPrincipal();
        System.out.println("当前登录用户是 :"+tbUser.getUsername());
        String perms = "myadd";
        SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo();
        List<String> permsList = new ArrayList<>();
        permsList.add(perms);
        auth.addStringPermissions(permsList);
        return auth;
    }
    //用户认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证方法");

        //判断账号是否存在
        UsernamePasswordToken token =(UsernamePasswordToken)authenticationToken;
        //通过账号查询
        String username = token.getUsername();
        TbUser tbUser = userService.findUserByUserName(username);
        //校验密码是否正确
        return tbUser == null ? null : new SimpleAuthenticationInfo(tbUser,tbUser.getPassword(),ByteSource.Util.bytes(tbUser.getSalt()), tbUser.getUsername());
    }
}
